package com.word.student.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.word.common.annotation.Excel;
import com.word.common.core.domain.entity.SysUser;
import com.word.common.core.text.Convert;
import com.word.common.utils.uuid.UUID;
import com.word.student.domain.WordFavorite;
import com.word.student.domain.WordGroupGet;
import com.word.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.word.common.annotation.Log;
import com.word.common.enums.BusinessType;
import com.word.student.domain.WordGet;
import com.word.student.service.IWordGetService;
import com.word.common.core.controller.BaseController;
import com.word.common.core.domain.AjaxResult;
import com.word.common.utils.poi.ExcelUtil;
import com.word.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 单词背诵Controller
 * 
 * @author wsccvb
 * @date 2025-05-21
 */
@Controller
@RequestMapping("/student/get")
@Slf4j
public class WordGetController extends BaseController
{
    private String prefix = "student/get";

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IWordGetService wordGetService;
    @GetMapping()
    public String get()
    {
        return prefix + "/get";
    }

    @GetMapping("/review")
    public String review()
    {
        return prefix + "/review";
    }

    /**
     * 查询单词背诵列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WordGet wordGet, String value)
    {
        startPage();
        HttpSession session = getSession();
        Set<WordGet> wordSet  = (Set<WordGet>) session.getAttribute("wordSet");
        if (wordSet == null) {
            wordSet = new LinkedHashSet<>();
        }
        if (null == wordGet) {
            wordGet = new WordGet();
        }
        if (value != null && !value.isEmpty()) {
            wordGet.setWordGroupGetValueList(Arrays.asList(value));
        }
        if (!wordGet.isEmpty()) {
            SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            String loginName = sysUser.getLoginName();
            sysUser = sysUserService.selectUserByLoginName(loginName);
            WordFavorite wordFavorite = new WordFavorite();
            wordFavorite.setUserId(sysUser.getUserId());
            List<WordGet> list = wordGetService.selectWordGetList(wordGet, wordFavorite);
            wordSet.addAll(list);
        }
        session.setAttribute("wordSet", wordSet);
        return getDataTable(new ArrayList<>(wordSet));
    }

    /**
     * 导出单词背诵列表
     */
    @Log(title = "单词背诵", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response)
    {
        try {
            HttpSession session = getSession();
            Set<WordGet> wordSet  = (Set<WordGet>) session.getAttribute("wordSet");

            // 验证数据
            if (wordSet == null || wordSet.isEmpty()) {
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("{\"error\": \"导出不能为空\"}");
                return;
            }

            // 初始化Excel工具类
            ExcelUtil<WordGet> util = new ExcelUtil<>(WordGet.class);
            util.init(new ArrayList<>(wordSet), "单词列表", "单词背诵数据", Excel.Type.EXPORT);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = UUID.fastUUID() + "_单词列表.xlsx";
            response.setHeader("Content-Disposition",
                    "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));

            // 执行导出
            util.exportExcel(response);

        } catch (Exception e) {
            log.error("导出失败", e);
            try {
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("{\"error\": \"" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }

    /**
     * 删除单词背诵
     */
    @Log(title = "单词背诵", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        List<Long> idsList = Arrays.asList(Convert.toStrArray(ids)).stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
        HttpSession session = getSession();
        Set<WordGet> wordSet  = (Set<WordGet>) session.getAttribute("wordSet");
        if (wordSet != null && !wordSet.isEmpty()) {
            wordSet.removeIf(wordGet -> idsList.contains(wordGet.getId()));
        }
        session.setAttribute("wordSet", wordSet);
        return AjaxResult.success("删除成功");
    }

    @GetMapping("/review-data")
    @ResponseBody
    public List<WordGet> getReviewData() {
        HttpSession session = getSession();
        Set<WordGet> wordSet = (Set<WordGet>) session.getAttribute("wordSet");
        return wordSet != null ? new ArrayList<>(wordSet) : new ArrayList<>();
    }

    /**
     * 清空Session中的wordSet
     */
    @PostMapping("/clearCache")
    @ResponseBody
    public AjaxResult clearCache()
    {
        getSession().removeAttribute("wordSet");
        return success("缓存已清除");
    }

    @PostMapping("/collect/{wordId}")
    @ResponseBody
    public AjaxResult toggleCollect(@PathVariable Long wordId) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        String loginName = sysUser.getLoginName();
        sysUser = sysUserService.selectUserByLoginName(loginName);
        WordFavorite wordFavorite = new WordFavorite();
        wordFavorite.setWordId(wordId);
        wordFavorite.setUserId(sysUser.getUserId());
        return AjaxResult.success(wordGetService.toggleCollect(wordFavorite));
    }

    @PostMapping("/update-error-words")
    @ResponseBody
    public AjaxResult updateErrorWords(@RequestBody Map<String, List<Long>> requestBody) {
        List<Long> errorIds = requestBody.get("errorIds");
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        String loginName = sysUser.getLoginName();
        sysUser = sysUserService.selectUserByLoginName(loginName);
        
        // 使用批量查询替换循环单次查询
        List<WordGet> wordGets = wordGetService.selectWordGetListByIds(errorIds, sysUser.getUserId());
        Set<WordGet> newSet = new LinkedHashSet<>(wordGets);
        
        getSession().setAttribute("wordSet", newSet);
        return AjaxResult.success("已更新错题列表");
    }
}
